<template>
  <div class="blog-manager-container">
    <!-- 搜索框 -->
    <div class="xw-block" style="display: flex;justify-content: center;padding-top: 30px;padding-bottom: 30px;">
      <div style="align-self: center;margin-left: 10px">
        <el-input v-model="posttitle" style="width: 300px; margin-right: 10px;" clearable @clear="clearSearch" placeholder="请输入想搜索的帖子标题？"></el-input>
        <el-button type="primary" style="margin-left: 5px" @click="search">搜 索</el-button>
      </div>
    </div>

    <!-- 博客列表 -->
    <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange" class="blog-table">
      <!-- 选择框 -->
      <el-table-column type="selection" width="55"></el-table-column>

      <!-- 标题列 -->
      <el-table-column label="标题">
        <template slot-scope="scope">
          <div style="width: 80%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
            <h4 class="ellipsis xw-enlarge" @click="toDetail(scope.row)" style="cursor: pointer; color: #409EFF;">
              {{ scope.row.title }}
            </h4>
          </div>
        </template>
      </el-table-column>

      <!-- 富文本内容列 -->
      <el-table-column label="内容" prop="content">
        <template slot-scope="scope">
          <div>
            <!-- 展示富文本内容 -->
            <span v-if="scope.row.isExpanded" v-html="scope.row.content"></span>
            <span v-else v-html="scope.row.content">{{ scope.row.content.slice(0, 100) }}...</span>

            <!-- 如果内容长度大于100，显示展开/收起按钮 -->
            <el-link
                v-if="scope.row.content.length > 100"
                type="primary"
                @click="toggleContent(scope.row)">
              {{ scope.row.isExpanded ? '收起' : '展开' }}
            </el-link>
          </div>
        </template>
      </el-table-column>

      <!-- 作者列 -->
      <el-table-column label="作者" prop="sendUserName"></el-table-column>

      <!-- 类型列 -->
      <el-table-column label="类型" prop="type"></el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作">
        <template slot-scope="scope">
          <!-- 根据用户角色判断是否显示编辑按钮 -->
          <el-button v-if="userRole === 'ROLE_ADMIN' || scope.row.sendUserName === user.nickName" @click="edit(scope.row)" size="small" type="primary">编辑</el-button>
          <!-- 根据用户角色判断是否显示删除按钮 -->
          <el-button v-if="userRole === 'ROLE_ADMIN' || scope.row.sendUserName === user.nickName" @click="del(scope.row.id)" size="small" type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- 分页 -->
    <el-pagination
        :current-page="pageRequest.pageNum"
        :page-size="pageRequest.pageSize"
        :total="total"
        :page-sizes="pageSizeArr"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next">
    </el-pagination>

    <!-- 按钮区域 -->
    <div class="button-container">
      <el-button type="danger" style="margin-left: 5px" @click="sendPost">新增</el-button>
      <!--      <el-button @click="delBatch" type="danger" :disabled="delIds.length === 0">批量删除</el-button>-->
    </div>

    <!-- MyDrawer 组件，编辑博客信息 -->
    <my-drawer ref="MyDrawer" :row="selectRow" @saveOrUpdate="update">
      <template #default>
        <el-form label-position="top" class="post-form">
          <el-form-item label='标题'>
            <el-input placeholder='请输入发布的帖子标题'
                      v-model='selectRow.title'></el-input>
          </el-form-item>
          <el-form-item label="帖子类型">
            <el-select v-model="selectRow.type" placeholder="请选择帖子类型">
              <el-option label="C语言" value="C语言"></el-option>
              <el-option label="HTML" value="HTML"></el-option>
              <el-option label="JAVA" value="JAVA"></el-option>
              <el-option label="Python" value="Python"></el-option>
              <el-option label="云计算" value="云计算"></el-option>
              <el-option label="软件工程" value="软件工程"></el-option>
              <el-option label="计算机科学与技术" value="计算机科学与技术"></el-option>
              <el-option label="信息安全" value="信息安全"></el-option>
              <el-option label="大数据" value="大数据"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label='发布内容'>
            <vue-editor v-model="selectRow.content"></vue-editor>
          </el-form-item>
        </el-form>
      </template>
    </my-drawer>

    <SendPost ref="SendPost" @sendSuccess="load"></SendPost>
  </div>
</template>

<script>
import MyDrawer from "@/components/MyDrawer.vue";
import SendPost from "@/components/SendPost.vue";
import { VueEditor } from "vue2-editor";
export default {
  data() {
    return {
      posttitle: '',
      delIds: [],
      selectRow: {},
      pageSizeArr: [10, 20, 30, 40],
      tableData: [],
      postTypeData: [],
      pageRequest: {
        pageNum: 1,
        pageSize: 10,
        q: {}
      },
      total: 0,
      // searchKeywords: '',
      user: JSON.parse(localStorage.getItem("user")),
      userRole: JSON.parse(localStorage.getItem("user"))? JSON.parse(localStorage.getItem("user")).role : '',
    };
  },
  components: {
    MyDrawer,
    SendPost,
    VueEditor
  },
  mounted() {
    this.load();
  },
  methods: {
    toDetail(scope) {
      //console.log("Navigating to detail with item ID:", item.id);
      this.$router.push({name: "postcodewithcomments",query: {id: scope.id}});
    },
    toggleContent(row) {
      row.isExpanded = !row.isExpanded;
    },
    load() {
      this.request.post("/postCode/page", this.pageRequest).then(res => {
        if (res.code === '200') {
          // 为每一行添加 isExpanded 字段，默认值为 false
          this.tableData = res.data.list.map(item => {
            item.isExpanded = false;  // 设置默认展开状态
            return item;
          });
          this.total = res.data.total;
        }
      });
    }
    ,

    clearSearch() {
      this.posttitle = '';  // 清空输入框
      this.pageRequest.q = {};  // 清空搜索条件
      this.load();  // 重新加载数据
    },

    search() {
      this.pageRequest.pageNum = 1;  // 重置页码
      if (this.posttitle.trim() === '') {
        // 如果没有输入标题，清空查询条件，显示所有帖子
        this.pageRequest.q = {};
      } else {
        // 如果输入了标题，按照标题搜索
        this.pageRequest.q.title = this.posttitle;
      }
      this.load();  // 重新加载数据
    },
    edit(row) {
      this.selectRow = row;
      this.$refs.MyDrawer.open(this.selectRow);
    },

    sendPost() {
      this.$refs.SendPost.open()
    },

    update() {
      this.request.post("/postCode", this.selectRow).then(res => {
        if (res.code === '200') {
          this.messageSuccess("修改成功");
          this.$refs.MyDrawer.close();  // 关闭抽屉
          this.load();  // 加载数据
        } else {
          this.messageError(res.msg);  // 显示错误消息
        }
      });
    },


    del(id) {
      this.request.delete(`/postCode/${id}`).then(res => {
        if (res.code === '200') {
          this.messageSuccess("删除成功");
          this.load();
        } else {
          this.messageError("删除失败");
        }
      });
    },

    handleSizeChange(size) {
      this.pageRequest.pageSize = size;
      this.load();
    },

    handleCurrentChange(pageNum) {
      this.pageRequest.pageNum = pageNum;
      this.load();
    },

    handleSelectionChange(e) {
      this.delIds = e.map(x => x.id);
    }
  }
};
</script>
